/**
 * Copyright (C) 2018-2019
 * All rights reserved, Designed By www.joolun.com
 * 注意：
 * 本软件为www.joolun.com开发研制，项目使用请保留此说明
 */
const WxParse = require('../../../public/wxParse/wxParse.js')
import Poster from '../../../components/wxa-plugin-canvas/poster/poster'
const { base64src } = require('../../../utils/base64src.js')
const app = getApp()

Page({
  data: {
    isChoice: '0', //设置默认选中
    config: app.globalData.config,
    product: null,
    currents: 1,
    cartNum: 1,
    goodsSpecData: [],
    shoppingCartCount: 0,
    shareShow: '',
    buyShow: '',
    modalService: '',
    num: 1,
		// 使用data数据对象设置样式名
    minusStatus: 'disabled',
    selSkuId: null,
    selImages: null,
    selSkuName: null
  },
  onLoad(options) {
    let id, skuId
    if (options.scene){//接受二维码中参数
      id = decodeURIComponent(options.scene)
    }else{
      id = options.id
      skuId = options.skuId
    }
    this.setData({
      id: id,
      skuId: skuId?skuId:0
    })
    app.initPage()
      .then(res => {
        this.goodsGet(id, skuId)
        this.shoppingCartCount()
      })
  },
  onShareAppMessage: function () {
    let product = this.data
    let title = product.name
    let imageUrl = product.picUrls[0]
    let path = 'pages/goods/goods-detail/index?id=' + product.id
    return {
      title: title,
      path: path,
      imageUrl: imageUrl,
      success: function (res) {
        if (res.errMsg == 'shareAppMessage:ok') {
          console.log(res.errMsg)
        }
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },
  goodsGet(id,skuId) {
    app.api.goodsGet(id, skuId)
      .then(res => {
        console.log('goods-detail', res)
        let product = res.data
        this.setData({
          product: product
        })
        // 默认第一条
        console.log('skuId', product.productSkuList[0].id)
        let checkedList = []
        // 组装选中属性
        product.specDtoList.forEach(spec => {
            spec.specAttrDtoList.forEach(attr =>{
              if(attr.checked){
                checkedList.push(attr.attrName)
              }
            })
        });
        this.selSkuId = product.productSkuList[0].id
        this.selSkuName = checkedList.join("+");
        //html转wxml
        WxParse.wxParse('description', 'html', product.description, this, 0)
      })
  },
  
  change: function (e) {
    this.setData({
      currents: e.detail.current + 1
    })
  },
  // 购买或加入购物车
  toDo(e) {
    let canDo = true
    if (canDo) {
      let product = this.data.product
      if (e.currentTarget.dataset.type == '1') {//加购物车
        if (this.data.shoppingCartId) {
          app.api.shoppingCartEdit({
            id: this.data.shoppingCartId,
            spuId: product.id,
            quantity: this.data.cartNum,
            addPrice: product.salesPrice,
            spuName: product.name,
            picUrl: product.picUrls ? product.picUrls[0]:''
          })
            .then(res => {
              wx.showToast({
                title: '修改成功',
                duration: 5000
              })
              this.shoppingCartCount();
            })
        } else {
          app.api.shoppingCartAdd({
            productId: product.id,
            skuId: this.selSkuId,
            quantity: this.data.num,
            addPrice: product.salePrice,
            productName: product.productName,
            images: this.selImages ? this.selImages : '',
            spec: this.selSkuName
          })
            .then(res => {
              wx.showToast({
                title: '添加成功',
                duration: 5000
              })
              this.setData({
                modalSku: false
              })
              this.shoppingCartCount()
            })
        }
      } else {//立即购买，前去确认订单
        if (this.data.product.stock <= 0) {
          wx.showToast({
            title: '抱歉，库存不足暂时无法购买',
            icon: 'none',
            duration: 2000
          })
          return;
        }
        /* 把参数信息异步存储到缓存当中 */
        wx.setStorage({
          key: 'param-orderConfirm',
          data: [{
            skuId: this.selSkuId,
            quantity: this.data.num,
            addPrice: product.salePrice,
            productName: product.productName,
            images: this.selImages ? this.selImages : ''
          }]
        })
        wx.navigateTo({
          url: '/pages/order/order-confirm/index'
        })
      }
    }
  },
  shoppingCartCount(){
    app.api.shoppingCartCount()
      .then(res => {
        let shoppingCartCount = res.data
        this.setData({
          shoppingCartCount: shoppingCartCount
        })
        //设置TabBar购物车数量
        app.globalData.shoppingCartCount = shoppingCartCount + ''
      })
  },
  operateCartEvent(){
    this.shoppingCartCount()
  },
  shareShow(){
    this.setData({
      shareShow: 'show'
    })
  },
  shareHide(){
    this.setData({
      shareShow: ''
    })
  },

  buyShow(){
    this.setData({
      buyShow: 'show',
      num : 1
    })
  },
  buyHide(){
    this.setData({
      buyShow: ''
    })
  },

  onPosterSuccess(e) {
    const { detail } = e
    this.setData({
      posterUrl: detail
    })
  },
  onPosterFail(err) {
    console.error(err);
  },
  hidePosterShow(){
    this.setData({
      posterShow: false,
      shareShow: ''
    })
  },
  /**
   * 异步生成海报
   */
  onCreatePoster() {
    
  },
  //点击保存到相册
  savePoster: function () {
    
  },
  handleContact(e) {
    console.log(e)
  },

  radioChange(e){
    let productSkuList = this.data.product.productSkuList
    let specDtoList = this.data.product.specDtoList
    let specName = e.currentTarget.dataset.model.name
    let checkedList = []
    specDtoList.forEach(spec => {
      if(spec.name===specName){
        spec.specAttrDtoList.forEach(attr =>{
          attr.checked = (attr.attrName == e.detail.value)
        })
      }
    });
    // 组装选中属性
    specDtoList.forEach(spec => {
        spec.specAttrDtoList.forEach(attr =>{
          if(attr.checked){
            checkedList.push(attr.attrName)
          }
        })
    });
    let checkedStr =  checkedList.join('_');
    this.setData({'selSkuName': checkedList.join('+')})
    this.selSkuName = checkedList.join('+');
    productSkuList.forEach(sku=>{
     if(sku.specifications==checkedStr){
      this.setData({'product.salePrice': sku.salePrice})
      this.selSkuId = sku.id
      this.selImages = sku.images
     }
    })
  },

  /* 点击减号 */
	bindMinus: function() {
		var num = this.data.num;
		// 如果大于1时，才可以减
		if (num > 1) {
			num --;
		}
		// 只有大于一件的时候，才能normal状态，否则disable状态
		var minusStatus = num <= 1 ? 'disabled' : 'normal';
		// 将数值与状态写回
		this.setData({
			num: num,
			minusStatus: minusStatus
		});
	},
	/* 点击加号 */
	bindPlus: function() {
		var num = this.data.num;
		// 不作过多考虑自增1
		num ++;
		// 只有大于一件的时候，才能normal状态，否则disable状态
		var minusStatus = num < 1 ? 'disabled' : 'normal';
		// 将数值与状态写回
		this.setData({
			num: num,
			minusStatus: minusStatus
		});
	},
	/* 输入框事件 */
	bindManual: function(e) {
		var num = e.detail.value;
		// 将数值与状态写回
		this.setData({
			num: num
    });
  }
})
